import React, { useState, useEffect } from "react";
import axios from "axios";

// 2. async
const request = async (url) => {
  const res = await axios.get(url);
  const data = res.data;
  if (data.code !== 200) {
    alert("服务器开小差了");
    return {};
  }
  return data.data;
};

//Hook封装
const useUser = id => {
  const [user, setUser] = useState({});
  // 加载
  const [loading, setLoading] = useState(true);
  const url = `https://xiaozhu.run/api/user/${id}`;

  const getUser = async () => {
    const user = await request(url);
    setLoading(false);
    setUser(user);
  };
  useEffect(() => getUser(), [id]);
  return [user, loading];
}
const GetUser = () => {
  const [id, setId] = useState(9527)
  const [user, loading] = useUser(id);
  const [user2, loading2] = useUser(id + 1);
  return (
    <div>
      <button onClick={() => { setId(id + 1); }}>Get User {id}</button>
      {loading && <span>Loading...</span>}
      <div>Email: {user.email}</div>
      <div>Name: {user.username}</div>

      <div>Email2: {user2.email}</div>
      <div>Name2: {user2.username}</div>
    </div>
  );
};
// 方式2
const Parent=props=>{
  return (
  <div>
  Parent<props.Component id={123}/>
  </div>);
}
export default ()=><Parent Component={()=><GetUser/>}/>;

